<template>
  <view class="app-page-wrap">
    <view class="top-search">
      <uni-easyinput prefixIcon="search" maxlength="50" v-model="search.name" placeholder="请选择客户"
        @click.native="openSelectSearch" disabled="true">
      </uni-easyinput>
      <select-search ref="selectSearchRef" :show="isShowSearchPop" :type="'radio'" :name="'customerName'"
        :value="'customerId'" :dataLists="customerList" :param="search.id" @search="searchCustomerFn"
        @cancel="cancelSelectFn" @submit="submitCustomerFn"></select-search>
    </view>
    <view class="content-box">
      <view class="ovewview">
        <view>
          <view class="label">现金</view>
          <view class="value">
            <text>{{ overview.cashBalance }}</text>
            元
          </view>
        </view>
        <view>
          <view class="label">承兑</view>
          <view class="value">
            <text>{{ overview.acceptanceBalance }}</text>
            元
          </view>
        </view>
      </view>
    </view>
    <view v-show="proShow">
      <view class="date-time-box" style="padding-bottom: 10px">
        <view class="date-time-item">
          <uni-datetime-picker v-if="isPickerVisible" type="datetime" ref="datePickerRefsStart" returnType="string"
            v-model="queryDateParam.startTime" placeholder="请选择开始日期时间" :clear-icon="false" :border="false" />
          <uni-datetime-picker v-if="isPickerVisible" type="datetime" ref="datePickerRefsEnd" returnType="string"
            v-model="queryDateParam.endTime" placeholder="请选择结束日期时间" :clear-icon="false" :border="false" />
          <uni-icons type="search" size="24" :color="iconColor" style="padding-right: 15px;"
            @touchstart="handleTouchStart" @touchend="handleTouchEnd" @click="searchData"></uni-icons>
        </view>
      </view>
      <view style="background-color: white">
        <u-tabs :list="proList" :current="curNow" @click="sectionChange"></u-tabs>
      </view>
      <view class="balance-wrap">
        <view class="text">合计</view>
        <view class="values">
          <view class="value">
            <text style="color: orange;font-size: 20px;">{{ Total.priceConvertTotal || 0.00 }}</text>
            万元
          </view>
          <view class="value">
            <text style="color: orange;font-size: 20px;">{{ Total.netWeightTotal || 0.00 }}</text>
            吨
          </view>
          <view class="value">
            <text style="color: orange;font-size: 20px;">{{ Total.carNumberTotal || 0 }}</text>
            车
          </view>
        </view>
      </view>
    </view>
    <view class="goods-list">
      <view class="item" v-for="(itemList, index) in List" :key="index">
        <view class="phxx-item">
          <view class="phxx-item-content">
            <view class="top">
              <view class="cname-box">
                <view class="gs">{{ itemList.customerName || '' }}</view>
              </view>
              <u-tag :text="itemList.coalSubtypeName || ''"></u-tag>
            </view>
            <view class="bottom" style="margin-top: 14rpx">
              <view class="items">
                <text class="til">车辆</text>
                <text class="val">{{ itemList.vehicleNo || '' }}</text>
              </view>
            </view>
            <view class="bottom">
              <view class="items">
                <text class="til">净重</text>
                <text class="val">{{ itemList.totalWeight || '' }}吨</text>
              </view>
            </view>
            <view class="bottom">
              <view class="items">
                <text class="til">金额</text>
                <text class="val">{{ itemList.priceTotal || '' }}元</text>
              </view>
            </view>
            <view class="bottom">
              <view class="items">
                <text class="til">时间</text>
                <text class="val">{{ itemList.grossTime || '' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <uni-load-more :status="isMore" />
    </view>
  </view>
</template>
<script>
  import config from '@/config';
  import { toast } from '@/utils/common';
  import { getTenantId, getDriverId } from '@/utils/auth';
  import { getCustomerList, getBalances, getProList, getDetailPage, getDetailList } from "@/api/saleDetailReport"

  export default {
    computed: {},
    data() {
      return {
        iconColor: '#0086b3',
        isPickerVisible: true,
        search: {
          id: undefined,
          name: undefined
        },
        overview: {},
        Total: {},
        List: [],
        isMore: 'more',
        customerList: [],
        cacheCustomerList: [],
        isShowSearchPop: false,
        customerName: null,
        queryDateParam: {
          pageNo: 1,
          pageSize: 10,
          startTime: '',
          endTime: '',
          productId: null,
          customerId: null
        },
        startTimeDefault: null,
        endTimeDefault: null,
        proList: [{
          proId: undefined,
          proName: undefined,
        }],
        curNow: 0,
        proShow: false,

      }
    },
    onShow() {
      //获取客户
      this.getClientList()
      //设置默认日期时间
      this.initDefaultTimes()
    },
    onReachBottom() {
      console.log(this.isMore);
      if (this.isMore === 'more') {
        this.queryDateParam.pageNo++
        this.getDetailList()
      }
    },
    onPullDownRefresh() {

    },
    methods: {
      handleTouchStart() {
        this.iconColor = '#99000a';
      },
      handleTouchEnd() {
        this.iconColor = '#0086b3';
      },
      //打开客户搜索弹框
      openSelectSearch() {
        this.$refs.selectSearchRef?.setDefaultValue(this.queryDateParam.customerId);
        this.customerList = JSON.parse(JSON.stringify(this.cacheCustomerList))
        this.isShowSearchPop = true
      },
      //客户搜索弹框关闭
      cancelSelectFn() {
        this.isShowSearchPop = false
      },
      //客户筛选
      searchCustomerFn(keyword) {
        this.customerList = this.cacheCustomerList.filter(e => e.customerName.includes(keyword))
      },
      //按照客户搜索页面信息
      submitCustomerFn(selectedCustomer) {
        this.search = {
          id: selectedCustomer.customerId,
          name: selectedCustomer.customerName
        }
        this.queryDateParam.customerId = selectedCustomer.customerId;
        this.customerName = selectedCustomer.customerName;
        this.queryDateParam.pageNo = 1
        this.isShowSearchPop = false; // 关闭弹框
        this.List = []
        //获取余额
        this.getBalances(this.queryDateParam.customerId)
        this.getProList(this.queryDateParam.customerId)
        this.initDefaultTimes()
        this.isPickerVisible = false; // 先隐藏组件
        this.$nextTick(() => {
          this.isPickerVisible = true; // 再显示组件
        });
      },
      //获取客户信息
      async getClientList() {
        const res = await getCustomerList(getDriverId())
        if (res.code === '200') {
          this.cacheCustomerList = res?.data || []
          this.customerList = JSON.parse(JSON.stringify(this.cacheCustomerList))
          if (this.customerList.length > 0) {
            this.queryDateParam.customerId = this.customerList[0].customerId;
            this.customerName = this.customerList[0].customerName;
            this.search = {
              id: this.queryDateParam.customerId,
              name: this.customerName
            }
            this.$refs.selectSearchRef?.setDefaultValue(this.queryDateParam.customerId);
            this.getBalances(this.queryDateParam.customerId)
            this.getProList(this.queryDateParam.customerId)
          }
        }
      },
      //获取客户余额
      async getBalances(customerId) {
        const res = await getBalances(customerId)
        if (res.code === '200') {
          this.overview = res.data || {}
        } else {
          toast(res.msg)
        }
      },
      //获取客户产品
      async getProList(customerId) {
        const res = await getProList(customerId)
        if (res.code === '200') {
          const List = res.data || {}
          if (List.length > 0) {
            this.proList = List.map(item => ({
              id: item.proId,
              name: item.proName
            }));
            this.curNow = 0
            this.queryDateParam.customerId = customerId
            this.queryDateParam.productId = this.proList[this.curNow].id;
            this.getDetailPage()
            this.getDetailList()
            this.isMore = 'more';
            this.proShow = true
          } else {
            this.List = []
            this.isMore = 'noMore';
            this.proShow = false
          }
        } else {
          toast(res.msg)
        }
      },
      //获取客户合计信息
      async getDetailPage() {
        const res = await getDetailPage(this.queryDateParam)
        if (res.code === 0) {
          this.Total = res.data || {}
        } else {
          toast(res.msg)
        }
      },
      //获取客户列表信息
      async getDetailList() {
        const res = await getDetailList(this.queryDateParam)
        if (res.code === 0) {
          const result = res.data.list || {}
          const total = res?.data?.total || 0
          this.List = [...this.List, ...result]
          this.setIsMore(total)
        } else {
          this.List = []
          toast(res.msg)
        }
        //停止下拉刷新
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
      },
      async searchData() {
        const newStart = this.queryDateParam.startTime;
        const newEnd = this.queryDateParam.endTime;

        // 临时保存原始值
        const originalStart = this.startTimeDefault;
        const originalEnd = this.endTimeDefault;

        // 立即恢复为上次有效值
        this.queryDateParam.startTime = originalStart;
        this.queryDateParam.endTime = originalEnd;

        const startTimestamp = new Date(newStart).getTime();
        const endTimestamp = new Date(newEnd).getTime();

        let isValid = true;
        if (newStart && newEnd) {
          if (endTimestamp < startTimestamp) {
            uni.showToast({ title: '结束时间不能早于开始时间', icon: 'none' });
            isValid = false;
          } else if ((endTimestamp - startTimestamp) / (86400000) > 31) {
            uni.showToast({ title: '最多筛选31天数据', icon: 'none' });
            isValid = false;
          }
        }

        if (isValid) {
          try {
            wx.showLoading({ title: '加载中...', mask: true });
            // 只有校验通过时才更新缓存值
            this.startTimeDefault = newStart;
            this.endTimeDefault = newEnd;
            this.queryDateParam.startTime = newStart;
            this.queryDateParam.endTime = newEnd;

            // 触发数据更新
            this.queryDateParam.pageNo = 1;
            await this.getDetailPage();
            this.List = [];
            await this.getDetailList();
          } finally {
            setTimeout(() => {
              wx.hideLoading();
            }, 500);
          }
        } else {
          // 强制更新picker显示
          this.isPickerVisible = false;
          this.$nextTick(() => {
            this.isPickerVisible = true;
          });
        }
      },
      initDefaultTimes() {
        const now = new Date();
        const startOfDay = new Date(now.setHours(0, 0, 0, 0));
        const endOfDay = new Date(now.setHours(23, 59, 59, 999));

        // 格式化为 "YYYY-MM-DD HH:MM:SS" 格式
        this.startTimeDefault = this.formatDate(startOfDay);
        this.endTimeDefault = this.formatDate(endOfDay);

        // 设置默认值
        this.queryDateParam.startTime = this.startTimeDefault;
        this.queryDateParam.endTime = this.endTimeDefault;
      },
      //分段器变化
      sectionChange(data) {
        this.queryDateParam.pageNo = 1
        this.List = []
        this.curNow = data.index;
        this.queryDateParam.productId = data.id;
        this.getDetailPage();
        this.getDetailList();
      },
      formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      setIsMore(total) {
        if (total == this.List.length) {
          this.isMore = 'noMore';
        } else {
          this.isMore = 'more';
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .app-page-wrap {
    .date-time-box {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .date-time-item {
      display: flex;
      align-items: center;
      /* 垂直居中 */
      gap: 10px;
      /* 给label和选择器之间添加间距 */
      background-color: #ffffff;
      border-bottom: 1px solid #F1F2F5;
    }

    .label {
      margin-right: 10px;
      /* 给label添加右边距 */
    }

    height: 100vh;

    .top-search {
      padding: 10px;
      display: flex;
      align-items: center;
      background-color: #ffffff;
      border-bottom: 1px solid #F1F2F5;
    }

    .balance-wrap {
      padding: 20px 0;
      margin: 7px 10px 10px 10px;
      background: white;
      text-align: center;
      /* 让合计居中 */
      background: linear-gradient(180deg, #dceeff, #ffffff 100%);
    }

    .text {
      font-weight: bold;
      font-size: 18px;
      margin-bottom: 10px;
      /* 给合计和下面的值之间留出间距 */
    }

    .values {
      padding-top: 10px;
      display: flex;
      /* 使用 flex 布局 */
      justify-content: space-around;
      /* 平均分布三个字段 */
      align-items: center;
      /* 垂直居中 */
    }

    .value {
      font-size: 18px;
      font-weight: bold;
      flex: 1;
      /* 每个字段占据相同宽度 */
      text-align: center;
      /* 文字居中 */
    }

    .content-wrap {
      .list+.list {
        margin-top: 10px;
      }

      .list {
        margin: 0 16px;
        border-radius: 8px;
        padding: 15px 10px 10px 10px;
        background-color: #ffffff;

        .title {
          font-size: 16px;
          font-weight: 500;
          color: #333333;
        }

        .content-balance {
          display: flex;
          justify-content: space-between;
          padding: 10px 0;
          border-bottom: 1px solid #F1F2F5;

          .label {
            color: #999999;
          }

          .value {
            color: #409EFE;
            font-weight: 600;
          }
        }

        .footer {
          display: flex;
          justify-content: flex-end;
          padding-top: 10px;
        }

        button {
          height: 32px !important;
          line-height: 32px !important;
          margin: 0 !important;
        }

        button[type="default"] {
          color: #409efe !important;
          border: 1px solid #409efe !important;
          background: #ffffff !important;
        }

        button+button {
          margin-left: 10px !important;
        }
      }
    }
  }

  .content-box {
    margin: 17.78 rpx;
    padding-bottom: 10px;

    .ovewview {
      display: flex;
      justify-content: space-between;

      >view {
        width: 50%;
        height: 70px;
        padding: 12px 0;
        border-radius: 4px;
        background: linear-gradient(180deg, #dceeff, #ffffff 100%);

        .label {
          text-align: center;
          font-size: 15px;
          color: #333333;
          padding-bottom: 6px;
        }

        .value {
          text-align: center;
          font-size: 14px;
          color: #666666;
        }

        text {
          color: #F78600;
          font-size: 20px;
          font-weight: 600;
        }
      }

      >view+view {
        margin-left: 10px;
      }
    }
  }

  .phxx-item {
    background: linear-gradient(180deg, #dceeff, #ffffff 100%);
  }

  .phxx-item-content {
    font-family: Arial, sans-serif;
  }

  .phxx-item-content .top {
    padding: 10px;
    font-size: 18px;
    border-bottom: 1px solid #9E9E9E;
    display: flex;
    justify-content: space-between;
  }

  .phxx-item-content .top .cname-box .gs {
    font-weight: 700;
    font-size: 18px;
  }

  .phxx-item-content .bottom {
    margin-top: 14 rpx;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .items {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .til {
      color: gray;
      font-size: 14px;
    }

    .val {
      color: black;
      font-size: 14px;
      margin-left: auto;
    }
  }
</style>